﻿using UnityEngine;

namespace CGF
{
    public class SizeLoop : MonoBehaviour
    {
        public bool randomStart;
        public float wait;
        public Vector2 minSize = new Vector2(6f, 25f);
        public Vector2 maxSize = new Vector2(6f, 60f);
        public float speed = 5;
        float sizeX, sizeY, r, delay;
        bool isStop, isPause;
        private RectTransform rectTransform;

        void Awake()
        {
            rectTransform = GetComponent<RectTransform>();
            if (randomStart)
            {
                r = Random.Range(0f, Mathf.PI * 2f);
            }
        }

        void Update()
        {
            if (isPause) return;

            if (wait > 0f)
            {
                if (delay > 0f)
                {
                    delay -= Time.deltaTime;
                }
                else
                {
                    r += speed * Time.deltaTime;
                    if (r >= Mathf.PI * 2f)
                    {
                        r = 0f;
                        delay = wait;
                        if (isStop)
                        {
                            isPause = true;
                        }
                    }
                }
            }
            else
            {
                r += speed * Time.deltaTime;
                if (r >= Mathf.PI * 2f)
                {
                    r = 0f;
                    if (isStop)
                    {
                        isPause = true;
                    }
                }
            }
            float sin = Mathf.Sin(r) * 0.5f + 0.5f;
            sizeX = minSize.x + sin * (maxSize.x - minSize.x);
            sizeY = minSize.y + sin * (maxSize.y - minSize.y);
            rectTransform.sizeDelta = new Vector3(sizeX, sizeY);
        }

        public void StartLoop()
        {
            isStop = false;
            isPause = false;
        }

        public void StopLoop()
        {
            isStop = true;
        }

        public void PauseLoop()
        {
            isPause = true;
        }
    }
}